import store from "../store";
import config from "./config.js";
import appUpdate from '@/uni_modules/leruge-app-update/js_sdk/leruge-app-update.js'
let BASE_URL = config.BASE_URL;
let buttonClicked = false
import qqmapsdk from '../sdk/qqmap-wx-jssdk.js'
let QQMapWX = new qqmapsdk({
	key: config.MAP_KEY
});

/**
 * 网络请求类
 */
export class Net { 
	/**
	 * get 请求
	 * @param url
	 * @param param
	 * @param isLoading 是否显示加载中，1显示0不显示
	 * @returns {Promise<any>}
	 * headers里面的Authorization为java项目token传参格式可按需删除
	 * 状态码401或302为后台token权限，此状态码直接跳转登录页，按需修改
	 */
	static get(url, param, isLoading = 1, showError = 0) {
		if (isLoading) {
			uni.showLoading({
				title: '加载中'
			});
		}
		let header = {
			'Content-Type': 'application/json'
		}
		if (uni.getStorageSync('token')) {
			header.authorization = 'Bearer ' + uni.getStorageSync('token')
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: BASE_URL + url, //仅为示例，并非真实接口地址。
				data: param,
				method: 'GET',
				header: header,
				success: (res) => {
					// console.log('res:', res.data)
					uni.hideLoading();
					if ((res.data.code === 400 || res.data.code === 'A0307') && showError != 1) {
						// console.log('111111111')
						uni.removeStorageSync('token')
						uni.removeStorageSync('user')
						uni.removeStorageSync('userType')
						if (!cancelBounce()) return;
						Toast.message("登陆过期或未登录")
						setTimeout(()=>{
							uni.reLaunch({
								url: '/pages/login/login',
							});
						},1500)
					} else if (res.data.code === 0) { 
						resolve(res.data);
					} else {
						if (showError === 1) {
							resolve(res.data)
							if (!cancelBounce()) return
						} else {
							reject(res.data.message || '系统错误')
						}
					}
				},
				fail: (res) => {
					console.log('res:', res)
					reject('请求失败');
				},
				complete: (res) => {

				}
			});
		});
	}

	/**
	 * post 请求
	 * @param url
	 * @param param
	 * @param isLoading 是否显示加载中，1显示0不显示
	 * @returns {Promise<any>}
	 * headers里面的Authorization为java项目token传参格式可按需删除
	 * 状态码401或302为后台token权限，此状态码直接跳转登录页，按需修改
	 */
	static post(url, param, isLoading = 1, showError = 0) {
		if (isLoading) {
			uni.showLoading({
				title: '加载中'
			});
		}
		let header = {
			'Content-Type': 'application/json'
		}
		if (uni.getStorageSync('token')) {
			header.authorization = 'Bearer ' + uni.getStorageSync('token')
		}
		// console.log('header:', header)
		return new Promise((resolve, reject) => {
			uni.request({
				url: BASE_URL + url, //仅为示例，并非真实接口地址。
				data: param,
				method: 'POST',
				header: header,
				success: (res) => {
					// console.log('res1111:', res.data.message)
					uni.hideLoading();
					if ((res.data.code === 400 || res.data.code === 'A0307') && showError != 1) {
						// uni.clearStorageSync();
						uni.removeStorageSync('token')
						uni.removeStorageSync('user')
						uni.removeStorageSync('userType')
						if (!cancelBounce()) return;
						Toast.message("登陆过期或未登录")
						setTimeout(()=>{
							uni.reLaunch({
								url: '/pages/login/login',
							});
						},1500)
					} else if (res.data.code === 0) {
						resolve(res.data);
					} else {
						Toast.message(res.data.message)
						if (showError == 1) {
							resolve(res.data);
							if (!cancelBounce()) return;
						} else {
							reject(res.data.message || '系统错误');
						}
					}
				},
				fail: (res) => {
					console.log('res:', res)
					reject('请求失败');
				},
				complete: (data) => {
					// console.log('data:', data)
				}
			});
		});
	}
	// 获取图片路径
	static imgPath(ids) {
		// console.log('图片:', res.data)
		return new Promise((resolve, reject) => {
			this.get('/fileInfo/getFileAuthPath', {
				fileIds: ids
			}).then(res => {
				let imgArray = res.data.map(el => {
					return el.path
				})
				resolve(imgArray);
			})
		})
	}
	/**
	 * 上传图片
	 * @param url
	 * @param param
	 * @param isLoading 是否显示加载中，1显示0不显示
	 * @returns {Promise<any>}
	 */
	static uploadFile(url, isLoading = 0) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1, // 默认9
				// sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
				// sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
				success(res) {
					if (isLoading) {
						uni.showLoading({
							title: '加载中'
						});
					}
					// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
					let tempFilePaths = res.tempFilePaths;
					uni.uploadFile({ //上传
						url: BASE_URL + url,
						filePath: tempFilePaths[0],
						name: "picture ",
						header: {
							"Content-Type": "multipart/form-data",
							'authorization': 'Bearer ' + uni.getStorageSync('token')
						},
						formData: {
							'picture ': 'file'
						},
						success(res) {
							let data = JSON.parse(res.data)
							resolve(data);
						},
						fail(res) {
							reject(res);
						},
						complete() {
							uni.hideLoading()
						}
					});
				},
				fail: (err) => {
					console.log('chooseImage fail', err)
					// #ifdef MP
					uni.getSetting({
						success: (res) => {
							let authStatus = res.authSetting['scope.album'];
							if (!authStatus) {
								uni.showModal({
									title: '授权失败',
									content: '需要从您的相册获取图片，请在设置界面打开相关权限',
									success: (res) => {
										if (res.confirm) {
											uni.openSetting()
										}
									}
								})
							}
						}
					})
					// #endif
				}
			});
		});
	}

	/**
	 * 上传多张图片
	 * @returns {Promise<any>}
	 */
	static uploadFiles(url, param, isLoading = 1) {
		if (isLoading) Toast.Indicator();
		return new Promise((resolve1, reject1) => {
			//将迭代体放在Promise里
			let promiseList = param.map((item) => {
				return new Promise((resolve, reject) => {
					axios({
						method: "post",
						url: url,
						params: item,
						withCredentials: true
					}).then(res => {
						resolve(res.data);
					}).catch(err => {
						reject(err)
						// console.log(err)
					});
				});
			})
			const result = Promise.all(promiseList).then((res) => {
				// 返回的res是个数据，对应promiseList中请求的结果，顺序与promiseList相同
				// 在这里也就是在线图片的url数组了
				return res;
			}).catch((error) => {
				// console.log(error);
			});
			// console.log('result',result)
			if (isLoading) Toast.IndicatorClose();
			resolve1(result);
		});
	}

	/**
	 * oss上传图片
	 * @param files  data
	 * @returns {Promise<any>}
	 */
	static ossUploadFile(files) {
		const _this = this;
		Toast.Indicator();
		const client = new OSS({
			region: "oss-cn-qingdao",
			accessKeyId: "LTAI4Fdbq7F4Q7U2E4Qpz2H4", //填入自己的id
			accessKeySecret: "1DIyyerM2KavkuSw7rS5yVDoiiSyM7", //填入自己的id
			bucket: "qianxianoss"
		});
		if (files) {
			if (files) {
				// console.log(files.type);
				if (!files.type.match("image.*")) {
					Toast.message("请上传图片格式的文件");
					Toast.IndicatorClose();
					return false;
				}
			}
			// 随机命名
			let random_name = "img/" + Common.random_string(6) + "_" + new Date().getTime() + "." + files.name.split(".")
				.pop();
			// 上传
			return new Promise((resolve, reject) => {
				client.multipartUpload(random_name, files).then((results) => {
					// 上传完成
					Toast.IndicatorClose();
					resolve(results);
					// console.log(results);
				}).catch((err) => {
					Toast.IndicatorClose();
					// console.log(err)
				});
			});
			// return client.multipartUpload(random_name, files);
		}
	}

}

/**
 * 弹窗交互工具类
 */
export class Toast {
	/**
	 * tips
	 * @param content
	 */
	static message(content = "", mask = true) {
		uni.showToast({
			title: content,
			duration: 2000,
			icon: "none",
			mask: mask
		});
	}

	static messageIcon(content = "", mask = true) {
		uni.showToast({
			title: content,
			duration: 2000,
			mask: mask
		});
	}

	/**
	 * 菊花转
	 * @param content
	 * @constructor
	 */
	static Indicator(content = "加载中") {
		if (store.state.ToastShow === true) return;
		store.commit('setToastShow', true)
		uni.showLoading({
			title: '加载中'
		});
	}

	/**
	 * 关闭菊花转
	 * @constructor
	 */
	static IndicatorClose() {
		store.commit('setToastShow', false)
		uni.hideLoading()
	}
}

/**
 * 公共方法类
 */
export class Common {
	// 是否需要冷更新
	static coldUpdataApp() {
		uni.getSystemInfo({
			success: res => {
				console.log("系统信息：", res)
				let appVersion = res.appWgtVersion
				console.log('本地版本号', appVersion)
				let appNowVersion = null
				Net.get('/consignorApi/ownConfig/consignorAppCurrentVersion').then(res => {
					console.log('线上版本号', res.data)
					appNowVersion = res.data 
					config.updateInfo.version = res.data
					if (appNowVersion > appVersion) {
						console.log('11111')
						Net.post('/consignorApi/consignor/appLogout',{},0,1).then(res=>{
							console.log('退出登录：', res)
							// console.log('22222')
							let updateInfo = config.updateInfo 
							appUpdate(updateInfo)
						})
					}
				})
			},
		});
	}
	/**
	 * 打开地图
	 * @param longitude  经度
	 * @param latitude   纬度
	 */
	static openMap(longitude, latitude, name) {
		if (longitude && latitude) {
			uni.openLocation({
				latitude: latitude,
				longitude: longitude,
				name: name,
				success: function() {
					console.log('success');
				}
			});
		} else {
			Toast.message('缺少经纬度')
		}
	}
	/**
	 * 预览图片
	 * @param list
	 * @param index  
	 */
	static viewImage(list, index) {
		console.log('list:', list, 'index:', index)
		uni.previewImage({
			urls: list,
			current: index
		});
	}
	// 打电话
	static call(phone) {
		if (phone) {
			uni.makePhoneCall({
				phoneNumber: phone
			})
		} else {
			Toast.message('未获取到电话')
		}
	}
	// 复制文本
	static copyText(str) {
		uni.setClipboardData({
			data: str
		})
	}
	// 获取颜色
	static getColor(value, list) {
		let color
		list.map(el => {
			if (el.value == value) {
				color = el.label
			}
		})
		return color
	}

	// 获取颜色
	static getCarType(value, list) {
		let type
		list.map(el => {
			if (el.children.length > 0) {
				el.children.map(item => {
					if (value == item.value) {
						type = item.label
					}
				})
			}
		})
		return type
	}

	/**
	 * 预览图片
	 * @param list
	 * @param index  
	 */
	static viewImage(list, index) {
		console.log('list:', list, 'index:', index)
		uni.previewImage({
			urls: list,
			current: index
		});
	}
	/**
	 * 格式化时间戳
	 * @param data
	 * @param format
	 * @returns {*}
	 */
	static formatTime(data, format) { //时间戳转日期 如：(date,"Y-M-D")或(date,"Y-M-D h:m:s")
		function formatNumber(n) {
			n = n.toString();
			return n[1] ? n : "0" + n;
		}

		let formateArr = ["Y", "M", "D", "h", "m", "s"];
		let returnArr = [];
		let date = new Date(data * 1000);
		returnArr.push(date.getFullYear());
		returnArr.push(formatNumber(date.getMonth() + 1));
		returnArr.push(formatNumber(date.getDate()));

		returnArr.push(formatNumber(date.getHours()));
		returnArr.push(formatNumber(date.getMinutes()));
		returnArr.push(formatNumber(date.getSeconds()));

		for (let i in returnArr) {
			format = format.replace(formateArr[i], returnArr[i]);
		}
		return format;
	}

	/**
	 * 获取时间戳
	 * @returns {number}
	 */
	static currentTime(num = 10) {
		return new Date().getTime().toString().substr(0, num);
	}

	/**
	 * 生成随机命名
	 * @returns {number}
	 */
	static random_string(len) {
		len = len || 32;
		var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
		var maxPos = chars.length;
		var pwd = "";
		for (let i = 0; i < len; i++) {
			pwd += chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	}


	/**
	 * 是否json字符串
	 * @param str
	 * @returns {boolean}
	 */
	static isJson(str) {
		if (typeof str === "string") {
			try {
				let obj = JSON.parse(str);
				if (typeof obj === "object" && obj) {
					return true;
				} else {
					return false;
				}
			} catch (e) {
				console.log("error：" + str + "!!!" + e);
				return false;
			}
		}
		// console.log("It is not a string!");
	}

	/**
	 * 浮点数精度计算加法，解决0.1+0.2!=0.3
	 * @returns {boolean}
	 */
	static add(a, b) {
		var c, d, e;
		try {
			c = a.toString().split(".")[1].length;
		} catch (f) {
			c = 0;
		}
		try {
			d = b.toString().split(".")[1].length;
		} catch (f) {
			d = 0;
		}
		return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e;
	}

	/**
	 * 浮点数精度计算减法，解决0.1+0.2!=0.3
	 * @returns {boolean}
	 */
	static sub(a, b) {
		var c, d, e;
		try {
			c = a.toString().split(".")[1].length;
		} catch (f) {
			c = 0;
		}
		try {
			d = b.toString().split(".")[1].length;
		} catch (f) {
			d = 0;
		}
		return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e;
	}

	/**
	 * 浮点数精度计算乘法，解决0.1+0.2!=0.3
	 * @returns {boolean}
	 */
	static mul(a, b) {
		var c = 0,
			d = a.toString(),
			e = b.toString();
		try {
			c += d.split(".")[1].length;
		} catch (f) {}
		try {
			c += e.split(".")[1].length;
		} catch (f) {}
		return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
	}

	/**
	 * 浮点数精度计算除法，解决0.1+0.2!=0.3
	 * @returns {boolean}
	 */
	static divi(a, b) {
		var c, d, e = 0,
			f = 0;
		try {
			e = a.toString().split(".")[1].length;
		} catch (g) {}
		try {
			f = b.toString().split(".")[1].length;
		} catch (g) {}
		return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), mul(c / d, Math.pow(
			10,
			f - e));
	}

	/**
	 * 复制文本内容str
	 * @returns {String}
	 */
	static copy(str) {
		if (str === '') {
			return Toast.message('未识别要复制的内容')
		}
		uni.setClipboardData({
			data: str,
			success: () => { //复制成功的回调函数
				Toast.message('复制成功')
			}
		});
	}

	/**
	 * 获取当前定位,并返回信息
	 * type： 1获取经纬度  2获取当前位置信息 3原始定位信息
	 * 
	 */
	static location(type = 1) {
		return new Promise((resolve, reject) => {
			uni.getSetting({
				success: (res) => {
					console.log('授权信息：', res)
					if (res.authSetting['scope.address'] != undefined && res.authSetting['scope.address'] != true) {
						wx.showModal({
							title: '是否授权当前位置',
							content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
							success: function(res) {
								console.log(res)
								if (res.cancel) {
									wx.showToast({
										title: '授权失败',
										icon: 'none',
										duration: 1000
									})
								} else if (res.confirm) {
									wx.openSetting({
										success: function(dataAu) {
											console.log(dataAu)
											if (dataAu.authSetting["scope.userLocation"] == true) {
												wx.showToast({
													title: '授权成功',
													icon: 'success',
													duration: 1000
												})
												uni.getLocation({
													type: 'gcj02',
													success: function(res) {
														var dw = {
															latitude: res.latitude,
															longitude: res.longitude
														}
														// 返回经纬度
														if (type == 1) {
															resolve(dw)
														}
														// 返回解析地址
														if (type == 2) {
															QQMapWX.reverseGeocoder({
																location: {
																	latitude: res.latitude,
																	longitude: res.longitude
																},
																success: function(data) {
																	// console.log("解析地址成功：", data);
																	resolve(data)
																},
																fail: function(data) {
																	uni.showToast({
																		title: '定位失败',
																		duration: 1500,
																		icon: "none"
																	})
																	resolve(data)
																},
																complete: function(data) {
																	// console.log(data);
																}
															})
														}
														if (type == 3) {
															resolve(res)
														}
													},
													fail: function(res) {

													},
													complete: function(res) {

													},
												});
											} else {
												wx.showToast({
													title: '授权失败',
													icon: 'none',
													duration: 1000
												})
											}
										}
									})
								}
							}
						})
					} else {
						uni.getLocation({
							type: 'gcj02',
							success: function(res) {
								console.log('res:', res)
								var dw = {
									latitude: res.latitude,
									longitude: res.longitude
								}
								// 返回经纬度
								if (type == 1) {
									resolve(dw)
								}
								// 返回解析地址
								if (type == 2) {
									QQMapWX.reverseGeocoder({
										location: {
											latitude: res.latitude,
											longitude: res.longitude
										},
										success: function(data) {
											// console.log("解析地址成功：", data);
											resolve(data)
										},
										fail: function(data) {
											uni.showToast({
												title: '定位失败',
												duration: 1500,
												icon: "none"
											})
											resolve(data)
										},
										complete: function(data) {
											// console.log(data);
										}
									})
								}
								if (type == 3) {
									resolve(res)
								}
							},
							fail: function(res) {

							},
							complete: function(res) {

							},
						});
					}
				}
			})

		})
	}
	// 判断是否开启定位权限
	static getIsLocation() {
		// 没有获取到位置，不停获取
		uni.getSetting({
			success(res) {
				if (!res.authSetting['scope.userLocation']) {
					uni.showModal({
						title: '是否授权当前位置',
						content: '请确认授权，否则无法正常使用',
						success(res) {
							if (res.confirm) {
								uni.openSetting({
									success() {
										// 跳到首页
									}
								})
							} else if (res.cancel) {
								// 跳到首页
							}
						}
					})
				} else {
					//用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位
					uni.showModal({
						title: '您手机定位功能没有开启',
						content: '请在系统设置中打开定位服务',
						confirmText: '确定',
						success() {
							// 跳到首页
						}
					})
				}
			}
		})
	}
}


/**
 * 数据存储类
 */
export class DataStore {
	/**
	 * 设置本地缓存
	 * @param key
	 * @param data
	 */
	static localSet(key, data) {
		if (typeof data === "object") data = JSON.stringify(data);
		// console.log(data)
		return localStorage.setItem(key, data);
	}

	/**
	 * 获取本地缓存
	 * @param key
	 * @returns {*}
	 */
	static localGet(key) {
		let data = localStorage.getItem(key);
		if (Common.isJson(data)) data = JSON.parse(data);
		return data;
	}

	/**
	 * 删除本地缓存
	 * @param key
	 */
	static localDel(key) {
		return localStorage.removeItem(key);
	}

	/**
	 * 清楚所有本地缓存
	 * @constructor
	 */
	static ClearLocal() {
		return localStorage.clear();
	}


	/**
	 * 设置essionStorage
	 * @param key
	 * @param data
	 */
	static SessionSet(key, data) {
		if (Common.isJson(data)) data = JSON.parse(data);
		return sessionStorage.setItem(key, data);
	}

	/**
	 * 获取sessionStorage
	 * @param key
	 * @constructor
	 */
	static SessionGet(key) {
		let data = sessionStorage.getItem(key);
		if (Common.isJson(data)) data = JSON.parse(data);
		return data;
	}

	/**
	 * 删除sessionStorage
	 * @param key
	 */
	static SessionDel(key) {
		return sessionStorage.removeItem(key);
	}

	/**
	 * 清楚所有sessionStorage
	 * @constructor
	 */
	static SessionClear() {
		return sessionStorage.clear();
	}
}


/**
 * 路由工具类
 */
export class Jump {

	/**
	 * 路由重定向，关闭当前页面，跳转到应用内的某个页面
	 * @param url
	 * @constructor
	 */
	static Redirect(url) {
		uni.redirectTo({
			url: url
		});
	}

	/**
	 * 直接跳转。保留当前页面
	 * @param url
	 * @constructor
	 */
	static Open(url) {
		uni.navigateTo({
			url: url
		});
	}


	/**
	 * 关闭当前页面，返回上一页面或多级页面
	 * @param index 返回的页面数，如果 delta 大于现有页面数，则返回到首页
	 */
	static Back(delta = 1) {
		uni.navigateBack({
			delta: delta
		});
	}


	/**
	 * 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
	 */
	static switchTab(url) {
		uni.switchTab({
			url: url //通常是首页/pages/index/index
		});
	}

	/**
	 * 关闭所有页面，打开到应用内的某个页面
	 * @param url  需要跳转的应用内页面路径
	 */
	static reLaunch(url) {
		uni.reLaunch({
			url: url
		});
	}

}

//防抖防多次跳转登录页
function cancelBounce() {
	if (!buttonClicked) {
		buttonClicked = true
		setTimeout(() => {
			buttonClicked = false
		}, 1000)
		return true
	} else {
		return false
	}
}